#include "manager_product.h"
#include "ui_manager_product.h"

manager_product::manager_product(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::manager_product)
{
    ui->setupUi(this);
   //insert_database("ice red tea",4);
   // select_database();
}



manager_product::~manager_product()
{
    delete ui;


}




int manager_product::insert_database(QString name,int price)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "first");
    db.setDatabaseName("./product.db");
    if (!db.open()) {
        qDebug() << "Failed to connect to database";
        return -1;
    }
    qDebug() << "Connected to database successfully" << endl;

    QSqlQuery query(db);

    // 查询最大id
    query.exec("SELECT MAX(id) FROM product");
    if (query.next()) {
        int last_id = query.value(0).toInt();
        int id = last_id + 1;
        qDebug() << "Last id:" << last_id;
        qDebug() << "New id:" << id;
        new_id=id;
        // 插入新数据
        query.prepare("INSERT INTO product (id, name, price) VALUES (:id, :name, :price)");
        query.bindValue(":id", id);
        query.bindValue(":name", name);
        query.bindValue(":price", price);

        if (!query.exec()) {
            qDebug() << "Failed to insert data:" << query.lastError().text();
        }
    } else {
        // 如果表是空的，则插入id为1的数据
        int id = 1;
        qDebug() << "Table is empty, inserting id:" << id;

        query.prepare("INSERT INTO product (id, name, ip) VALUES (:id, :name, :ip)");
        query.bindValue(":id", id);
        query.bindValue(":name", name);
        query.bindValue(":price", price);

        if (!query.exec()) {
            qDebug() << "Failed to insert data:" << query.lastError().text();
        }
    }
    select_database();
    return new_id;
}



    void manager_product::select_database()
    {


        QSqlDatabase db;

        // 连接SQLite数据库
        db = QSqlDatabase::addDatabase("QSQLITE","first");
        db.setDatabaseName("./product.db"); // 替换为你的数据库文件路径
        if (!db.open()) {
            qDebug() << "Failed to connect to database";
            //return;
        }else
            qDebug()<<"连接数据库成功"<<endl;
        QSqlQuery query(db);


       query.exec("SELECT * FROM product");//select为遍历


        while(query.next()) {
            int id = query.value(0).toInt();//value（0）表示低0列
            QString name = query.value(1).toString();
            int price = query.value(2).toInt();
            qDebug() << "ID:" << id << " Name:" << name << " price:" <<price;

            }




        // 创建read write模型
            QSqlTableModel *model = new QSqlTableModel(this,db);
                model->setTable("product");
                if(!model->select())
                {
                    qDebug() << "数据查询失败!!" << model->lastError().text();
                    return;
                }

            int rowCount = model->rowCount();
              qDebug() << "Number of rows in the result set:" << rowCount;
                //equipment_num=rowCount;


              // 获取当前列数
              int currentColumnCount = model->columnCount();

              // 在当前列数之后插入新列
              model->insertColumn(currentColumnCount);

              // 设置新列的标题
              model->setHeaderData(currentColumnCount, Qt::Horizontal, QObject::tr("button action"));



              // 必须要设置此项，否则样式表的hover无法生效
                  ui->product_education->setMouseTracking(true);
                  // 构造函数中传入按钮列表即可添加任意个按钮
                  m_btnDelegate = new QMyTableViewBtnDelegate(QStringList()<<"编辑"<<"删除", this);
                  // 为指定列设置代理
                  ui->product_education->setItemDelegateForColumn(3, m_btnDelegate);


              // 连接信号槽，根据需要添加
              connect(m_btnDelegate, &QMyTableViewBtnDelegate::editData, this, [=](const QModelIndex &index){
                  QMessageBox::information(this, "提示", QString("编辑第 %1 行数据").arg(index.row()+1));
              });//editdata是自定义的信号
           /*   connect(m_btnDelegate, &QMyTableViewBtnDelegate::deleteData, this, [=](const QModelIndex &index){
                  QMessageBox::information(this, "提示", QString("删除第 %1 行数据").arg(index.row()+1));
              });
    */


              connect(m_btnDelegate, &QMyTableViewBtnDelegate::deleteData, this, [=](const QModelIndex &index){
                  // 获取要删除的行的id
                  QVariant idValue = model->data(model->index(index.row(), 0)); // 假设 "id" 列是查询结果的第一列
                  if (!idValue.isValid() || idValue.isNull()) {
                      QMessageBox::warning(this, "警告", "无法获取要删除的行的ID。");
                      return;
                  }

                  int id = idValue.toInt(); // 将QVariant转换为int，假设ID是整数类型

                  // 准备并执行删除语句
                  QSqlQuery query(db);
                  query.prepare("DELETE FROM product WHERE id = :id"); // 假设表名为 "users"
                  query.bindValue(":id", id);
                  if (!query.exec()) {
                      QMessageBox::critical(this, "错误", "删除数据失败：" + query.lastError().text());
                      return;
                  }

                    select_database();


                  // 可选：通知用户删除成功
                  QMessageBox::information(this, "提示", QString("已删除ID为 %1 的行。").arg(id));
              });



            ui->product_education->setModel(model);
            ui->product_education->resizeColumnsToContents(); // 调整列宽度使数据能够完全显示


}








void manager_product::on_return_2_clicked()
{
    this->parentWidget()->show();
    this->hide();
}

void manager_product::on_refresh_clicked()
{
    select_database();
}
void manager_product::on_pushButton_clicked()
{
    bool ok;
    QString name = QInputDialog::getText(this, "Input Dialog", "Enter the name:", QLineEdit::Normal, "", &ok);
    if (!ok) {
        // 用户取消了输入
        return;
    }

    name = name.trimmed(); // 去除名称两侧的空格

        QString priceStr = QInputDialog::getText(this, "Input Dialog", "Enter the price:", QLineEdit::Normal, "0", &ok); // 默认显示 "0"
        if (!ok || priceStr.isEmpty()) {
            // 用户取消了输入或输入为空
            return;
        }

        bool conversionOk;
        int price = priceStr.toInt(&conversionOk); // 尝试将输入的字符串转换为整数
        if (!conversionOk) {
            // 输入的不是有效的整数
            QMessageBox::warning(this, "Invalid Input", "The price must be a valid integer.");
            return;
        }

    qDebug() << "Name:" << name << "Price:" << price; // 现在 price 将包含正确的双精度浮点数价格
    insert_database(name, price); // 确保 insert_database 函数可以接受 double 类型的价格参数
}
